/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Control.Control;
import DataBase.ServicioMenu;
import Logic.Log;
import Logic.Regla;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Fernando
 */
public class GUI_Rules extends javax.swing.JPanel {

    Control control = Control.getInstance();

    /**
     * Creates new form GUI_Rules
     */
    public GUI_Rules() {
        initComponents();
        /*if (!(control.getSELECTED_SERVER().equals(""))) {
         server1.setText(control.getSELECTED_SERVER());
         }*/
        
        this.tRules.getTableHeader().setReorderingAllowed(false);
        this.cargarTablaReglas();
        ServicioMenu su = control.getServicioMenu();
        this.tTables.getTableHeader().setReorderingAllowed(false);
        this.llenarCombo(cmb, su.getTS());
        this.alterPanel(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        cmb = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        selectTable = new javax.swing.JButton();
        textabla = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        textColumn = new javax.swing.JLabel();
        cmb2 = new javax.swing.JComboBox();
        cmb3 = new javax.swing.JComboBox();
        espR = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        createRule = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tTables = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        newRule = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tRules = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("CREATE RULE"));

        cmb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbActionPerformed(evt);
            }
        });

        jLabel2.setText("Tablespace:");

        selectTable.setText("SELECT TABLE");
        selectTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectTableActionPerformed(evt);
            }
        });

        textabla.setText("No table selected.");

        jLabel3.setText("Table:");

        jLabel4.setText("Column:");

        textColumn.setText("No column selected.");

        cmb2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmb2ActionPerformed(evt);
            }
        });

        jLabel5.setText("Condition:");

        createRule.setText("CREATE RULE");
        createRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createRuleActionPerformed(evt);
            }
        });

        tTables = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false; //Disallow the editing of any cell
            }
        };
        tTables.getTableHeader().setReorderingAllowed(false);
        tTables.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "TABLES"
            }
        ));
        tTables.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tTablesMousePressed(evt);
            }
        });
        jScrollPane2.setViewportView(tTables);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(138, 138, 138)
                .addComponent(createRule, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(120, 120, 120))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(11, 11, 11)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(textabla)
                                            .addComponent(textColumn)))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cmb, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addComponent(selectTable, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cmb2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(cmb3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(espR)))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textabla)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textColumn))
                .addGap(35, 35, 35)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(selectTable)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addGap(1, 1, 1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmb2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmb3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(espR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addComponent(createRule)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Server Rules"));

        newRule.setText("CREATE RULE");
        newRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newRuleActionPerformed(evt);
            }
        });

        tRules = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false; //Disallow the editing of any cell
            }
        };
        this.tRules.getTableHeader().setReorderingAllowed(false);
        tRules.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Tablespace", "Table", "Column", "Rule"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, false, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tRules);
        tRules.getColumnModel().getColumn(4).setPreferredWidth(120);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(newRule)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(newRule)
                .addGap(6, 6, 6))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void newRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRuleActionPerformed
        /*GUI_NewRule gnr = new GUI_NewRule(this);
        gnr.setVisible(true);*/
        this.alterPanel(true);
    }//GEN-LAST:event_newRuleActionPerformed

    private void tTablesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tTablesMousePressed
        this.textColumn.setText("No column selected.");
    }//GEN-LAST:event_tTablesMousePressed

    private void selectTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectTableActionPerformed
        //this.cmb3.setEnabled(false);
        int r = tTables.getSelectedRow();
        if (r == -1) {
            JOptionPane.showMessageDialog(null, "There is not table selected.");
        } else {

            String tabla = (String) tTables.getValueAt(r, 0);
            this.textabla.setText(tabla);
            this.llenarCombo(cmb2, control.getServicioMenu().getColTable(tabla));
        }
    }//GEN-LAST:event_selectTableActionPerformed

    private void cmbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbActionPerformed
        this.cmb3.setEnabled(false);
        this.textabla.setText("No table selected.");
        this.textColumn.setText("No column selected.");
        cargarTabla(control.getServicioMenu().gettableTS((String) cmb.getSelectedItem()));
    }//GEN-LAST:event_cmbActionPerformed

    private void cmb2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb2ActionPerformed
        int r = tTables.getSelectedRow();
        String tabla = this.textabla.getText();
        this.textColumn.setText("No column selected.");

        if (cmb2.getSelectedItem() != null && tabla != null) {
            String type = control.getServicioMenu().getColType(tabla, (String) cmb2.getSelectedItem());
            this.textColumn.setText(cmb2.getSelectedItem().toString());
            this.cmb3.setEnabled(true);
            cmb3.removeAllItems();
            if (type.equals("NUMBER") || type.equals("FLOAT")) {
                //TODO
                cmb3.addItem(">");
                cmb3.addItem(">=");
                cmb3.addItem("<");
                cmb3.addItem("<=");
                cmb3.addItem("=");
                cmb3.addItem("!=");

            } else {
                cmb3.addItem("=");
                cmb3.addItem("!=");
            }
        }
    }//GEN-LAST:event_cmb2ActionPerformed

    private void createRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createRuleActionPerformed
        if (!(espR.getText().equals(""))&& (cmb2.getItemCount()>0)) {
            if (this.textColumn.getText().equals(cmb2.getSelectedItem().toString())) {
                String dato = this.espR.getText();
                String serv;
                String tsp;
                String tbl;
                String col;
                boolean exito = true;
                if (cmb3.getItemCount() != 2) {
                    exito = this.esNumero(dato);
                }
                if (!exito) {
                    JOptionPane.showMessageDialog(this, "This is not a number.");
                } else {
                    serv = control.getSELECTED_SERVER();
                    tsp = cmb.getSelectedItem().toString();
                    tbl = this.textabla.getText();
                    col = this.textColumn.getText();
                    String uno = cmb3.getSelectedItem().toString();
                    String dos = espR.getText();
                    int numeroRegla = this.control.getReglas().size() + 1;
                    Regla rgl = new Regla(serv, tsp, tbl, col, uno, dos, numeroRegla);
                    this.control.getReglas().add(rgl);

                    try {
                        this.control.actualizarArchivo();
                    } catch (FileNotFoundException ex) {
                        JOptionPane.showMessageDialog(this, "e1");
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(this, "e2");
                    }
                    this.cargarTablaReglas();
                    
                    //Logs
                    Log log = new Log(new Date(),control.getUser(),control.getSELECTED_SERVER(),Log.CREATE_RULE,rgl.toLog());
                    control.insertLog(log);
                    control.saveLogs();
                    
                    JOptionPane.showMessageDialog(this, "New Rule created.");
                    this.alterPanel(false);

                }
            } else {
                JOptionPane.showMessageDialog(this, "The condition does not match with the column selected.");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Condition/Column is empty.");
        }
    }//GEN-LAST:event_createRuleActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmb;
    private javax.swing.JComboBox cmb2;
    private javax.swing.JComboBox cmb3;
    private javax.swing.JButton createRule;
    private javax.swing.JTextField espR;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton newRule;
    private javax.swing.JButton selectTable;
    private javax.swing.JTable tRules;
    private javax.swing.JTable tTables;
    private javax.swing.JLabel textColumn;
    private javax.swing.JLabel textabla;
    // End of variables declaration//GEN-END:variables



    public void cargarTabla(ArrayList list) {

        for (int i = 0; i < ((DefaultTableModel) tTables.getModel()).getRowCount();) {
            ((DefaultTableModel) tTables.getModel()).removeRow(i);
        }
        for (int i = 0; i < list.size(); i++) {
            String ser = (String) list.get(i);
            ((DefaultTableModel) tTables.getModel()).addRow(new Object[]{ser});
        }
    }

    public void cargarTablaReglas() {

        for (int i = 0; i < ((DefaultTableModel) tRules.getModel()).getRowCount();) {
            ((DefaultTableModel) tRules.getModel()).removeRow(i);
        }

        //agrega lo que haya en el arraylist
        for (int i = 0; i < control.getReglas().size(); i++) {
            if(control.getReglas().get(i).getServidor().equals(control.getSELECTED_SERVER()))
            {
                String ser = control.getReglas().get(i).getNombre();
                String ser2 = control.getReglas().get(i).getTablespace();
                String ser3 = control.getReglas().get(i).getTabla();
                String ser33 = control.getReglas().get(i).getColummna();
                String ser4 = control.getReglas().get(i).getColummna()+" "+control.getReglas().get(i).getCondicion()+" "+control.getReglas().get(i).getPredicado();
                ((DefaultTableModel) tRules.getModel()).addRow(new Object[]{ser,ser2,ser3,ser33,ser4});
            }
            
            
        }
    }

    public void llenarCombo(JComboBox jcb, ArrayList s) {
        jcb.removeAllItems();
        for (int i = 0; i < s.size(); i++) {
            Object ser = s.get(i);
            jcb.addItem(ser);
        }
    }

    public boolean esNumero(String hilera) {
        try {
            Double.parseDouble(hilera);
        } catch (Exception E) {
            return false;
        }
        return true;
    }
    public void alterPanel(boolean sign){
    for (int i = 0; i < jPanel1.getComponents().length; i++) {
            jPanel1.getComponent(i).setEnabled(sign);
        }
    this.tTables.setVisible(sign);
    }
}
